package cn.com.open.opensaas.scoreservice.datasource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.lang.reflect.SourceLocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Order(-1)// 保证该AOP在@Transactional之前执行
public class DataSourceAspect {
    private static Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

    @Pointcut("execution(* cn.com.open.opensaas.scoreservice.service.*.*(..))")
    public void dataSourcePointcut(){}


    @Before("dataSourcePointcut()")
     public void setDataSourceKey(JoinPoint joinPoint){
        MethodSignature signature =  (MethodSignature) joinPoint.getSignature();;
        Method method = signature.getMethod();
        Object target = joinPoint.getTarget();
        logger.info("切入点: " + target.getClass().getName() + "类中" + method.getName() + "方法");
        if(method.getName().startsWith("add")
                || method.getName().startsWith("create")
                || method.getName().startsWith("archive")
                || method.getName().startsWith("save")
                || method.getName().startsWith("edit")
                || method.getName().startsWith("read")
                || method.getName().startsWith("update")
                || method.getName().startsWith("delete")
                || method.getName().contains("Token")
                || method.getName().contains("Authentication")
                || method.getName().startsWith("remove")){
            logger.info("切换到: master");
            DataSourceSwitcher.setDataSource("master");
        }else  {
            logger.info("切换到: slave");
            DataSourceSwitcher.setDataSource("slave");
        }
    }



}
